package top.krwlc.server.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.krwlc.server.dao.UserDao;
import top.krwlc.server.message.UserMessage;
import top.krwlc.server.pojo.User;

import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * krwlc
 * top.krwlc.server.service
 *
 * @author Lanscarlos
 * @since 2022-04-05 14:43
 */
@Service
public class UserService {

    @Autowired
    public UserDao dao;

    @Autowired
    public UserMessage message;

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     * */
    public ServiceResult login(String username, String password) {
        User user = dao.select(username, password);
        int status = user != null ? 0x200 : 0x000;
        String message = user != null ? this.message.LOGIN_SUCCEEDED : this.message.LOGIN_FAILED;
        return ServiceResult.pass(status, message, user);
    }

    /**
     * 用户注册
     *
     * @param display 昵称
     * @param password 密码
     * @return
     * */
    public ServiceResult register(
            String display,
            String password,
            String name,
            String identityCode,
            String phone
    ) {
        int status;
        String message;
        User user = null;
        if (dao.checkDisplay(display)) {
            status = 0x101;
            message = this.message.REGISTER_DUPLICATE_DISPLAY;
        }
        else if (dao.checkIdentityCode(identityCode)) {
            status = 0x104;
            message = this.message.REGISTER_DUPLICATE_IDENTITY_CODE;
        }
        else if (dao.checkPhone(phone)) {
            status = 0x105;
            message = this.message.REGISTER_DUPLICATE_PHONE;
        }
        else {
            try {
                user = new User(UUID.randomUUID().toString(), display, password, name, identityCode, phone);
                if (dao.insert(user)) {
                    status = 0x200;
                    message = this.message.REGISTER_SUCCEEDED;
                } else {
                    status = 0x106;
                    message = this.message.REGISTER_FAILED;
                }
            } catch (Exception e) {
                e.printStackTrace();
                status = 0x107;
                message = this.message.REGISTER_FAILED_INVALID_IDENTITY_CODE;
            }
        }
        return ServiceResult.pass(status, message, user);
    }

}
